package com.example.miaosha.controller;

import com.example.miaosha.constant.Constant;
import com.example.miaosha.entity.R;
import com.example.miaosha.entity.User;
import com.example.miaosha.service.IUserService;
import com.example.miaosha.util.MD5Util;
import com.example.miaosha.util.RedisUtil;
import com.example.miaosha.util.StringUtil;
import com.example.miaosha.util.UUIDUtil;
import com.example.miaosha.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户登录控制器
 * @author kangnan
 * @date 2021/5/10 0:45
 **/
@RestController
@RequestMapping("/")
public class LoginController {

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 用户登录
     * @return
     */
    @RequestMapping("/login")
    public R login(@RequestBody UserVo userVo){
        if (userVo == null) {
            return R.error();
        }
        if (StringUtil.isEmpty(userVo.getAccount())) {
            return R.error("参数account不可为空！");
        }
        if (StringUtil.isEmpty(userVo.getPassword())) {
            return R.error("参数password不可为空！");
        }

        User user = userService.findByAccount(userVo.getAccount());
        if (user == null) {
            return R.error("用户不存在！");
        }
        if (!user.getPassword().equals(MD5Util.backMd5(userVo.getPassword()))) {
            return R.error("账号或密码错误！");
        }

        // 生成token
        String token = UUIDUtil.genUuid();
        redisUtil.set(Constant.REDIS_TOKEN_PREFIX, token, user, Constant.REDIS_TOKEN_EXPIRE);

        return R.ok(token);
    }
}
